﻿using System;
using System.Windows.Input;
using System.Windows.Controls;
using System.Linq;
using TodoLister.Commands;
using TodoLister.Models;
using TodoLister.Services;
using System.Windows.Controls.Primitives;
using System.Windows;
using System.Threading.Tasks;

namespace TodoLister.ViewModels
{
    /// <summary>
    /// 主窗口ViewModel
    /// </summary>
    public class MainViewModel : ViewModelBase
    {
        private readonly IFileStorageService _storageService;
        private TodoList _todoList;
        private TodoItem _selectedItem;
        private string _newTitle;
        private string _newContent;
        private TodoPriority _selectedPriority;
        private bool _isAddPanelExpanded = false;  // 默认折叠
        private TodoFilterType _selectedFilter = TodoFilterType.Todo;

        /// <summary>
        /// 添加面板是否展开
        /// </summary>
        public bool IsAddPanelExpanded
        {
            get => _isAddPanelExpanded;
            set => SetProperty(ref _isAddPanelExpanded, value);
        }

        /// <summary>
        /// 选中的过滤类型
        /// </summary>
        public TodoFilterType SelectedFilter
        {
            get => _selectedFilter;
            set
            {
                if (SetProperty(ref _selectedFilter, value))
                {
                    // 触发过滤
                    TodoList.ApplyFilter(value);
                    // 通知属性变更
                    OnPropertyChanged(nameof(TodoCount));
                    OnPropertyChanged(nameof(DailyCount));
                    OnPropertyChanged(nameof(CompletedCount));
                    OnPropertyChanged(nameof(TodoText));
                    OnPropertyChanged(nameof(DailyText));
                    OnPropertyChanged(nameof(CompletedText));
                }
            }
        }

        /// <summary>
        /// 全部待办数量
        /// </summary>
        public int TodoCount => TodoList.TodoCount;

        /// <summary>
        /// 今日待办数量
        /// </summary>
        public int DailyCount => TodoList.DailyCount;

        /// <summary>
        /// 已完成数量
        /// </summary>
        public int CompletedCount => TodoList.CompletedCount;

        /// <summary>
        /// 全部待办显示文本
        /// </summary>
        public string TodoText => $"To-do ({TodoCount})";

        /// <summary>
        /// 今日待办显示文本
        /// </summary>
        public string DailyText => $"Daily ({DailyCount})";

        /// <summary>
        /// 已完成显示文本
        /// </summary>
        public string CompletedText => $"Completed ({CompletedCount})";

        /// <summary>
        /// 文件存储服务
        /// </summary>
        public IFileStorageService StorageService => _storageService;

        /// <summary>
        /// 待办事项列表
        /// </summary>
        public TodoList TodoList
        {
            get => _todoList;
            private set => SetProperty(ref _todoList, value);
        }

        /// <summary>
        /// 选中的待办事项
        /// </summary>
        public TodoItem SelectedItem
        {
            get => _selectedItem;
            set
            {
                if (SetProperty(ref _selectedItem, value))
                {
                    ((RelayCommand)RemoveItemCommand).RaiseCanExecuteChanged();
                }
            }
        }

        /// <summary>
        /// 新待办事项标题
        /// </summary>
        public string NewTitle
        {
            get => _newTitle;
            set
            {
                if (SetProperty(ref _newTitle, value))
                {
                    ((RelayCommand)AddItemCommand).RaiseCanExecuteChanged();
                }
            }
        }

        /// <summary>
        /// 新待办事项内容
        /// </summary>
        public string NewContent
        {
            get => _newContent;
            set => SetProperty(ref _newContent, value);
        }

        /// <summary>
        /// 选中的优先级
        /// </summary>
        public TodoPriority SelectedPriority
        {
            get => _selectedPriority;
            set => SetProperty(ref _selectedPriority, value);
        }

        /// <summary>
        /// 所有优先级值
        /// </summary>
        public TodoPriority[] PriorityValues { get; } = Enum.GetValues(typeof(TodoPriority))
                                                           .Cast<TodoPriority>()
                                                           .ToArray();

        /// <summary>
        /// 添加待办事项命令
        /// </summary>
        public ICommand AddItemCommand { get; }

        /// <summary>
        /// 删除待办事项命令
        /// </summary>
        public ICommand RemoveItemCommand { get; }

        /// <summary>
        /// 保存待办事项命令
        /// </summary>
        public ICommand SaveItemsCommand { get; }

        /// <summary>
        /// 加载待办事项命令
        /// </summary>
        public ICommand LoadItemsCommand { get; }

        /// <summary>
        /// 按优先级排序命令
        /// </summary>
        public ICommand SortByPriorityCommand { get; }

        /// <summary>
        /// 按时间排序命令
        /// </summary>
        public ICommand SortByTimeCommand { get; }

        /// <summary>
        /// 显示菜单命令
        /// </summary>
        public ICommand ShowMenuCommand { get; }

        /// <summary>
        /// 切换添加面板命令
        /// </summary>
        public ICommand ToggleAddPanelCommand { get; }

        /// <summary>
        /// 默认构造函数
        /// </summary>
        public MainViewModel(IFileStorageService storageService)
        {
            _storageService = storageService;
            TodoList = new TodoList();

            AddItemCommand = new RelayCommand(ExecuteAddItem, CanExecuteAddItem);
            RemoveItemCommand = new RelayCommand(ExecuteRemoveItem, CanExecuteRemoveItem);
            SaveItemsCommand = new RelayCommand(async () => await ExecuteSaveItems());
            LoadItemsCommand = new RelayCommand(ExecuteLoadItems);
            ShowMenuCommand = new RelayCommand<TodoItem>(ExecuteShowMenu);
            SortByPriorityCommand = new RelayCommand(ExecuteSortByPriority);
            SortByTimeCommand = new RelayCommand(ExecuteSortByTime);
            ToggleAddPanelCommand = new RelayCommand(ExecuteToggleAddPanel);

            // 尝试加载已保存的待办事项
            ExecuteLoadItems();
        }

        private bool CanExecuteAddItem()
        {
            return !string.IsNullOrWhiteSpace(NewTitle);
        }

        private async void ExecuteAddItem()
        {
            TodoList.AddItem(NewTitle, NewContent, SelectedPriority);

            // 清空输入
            NewTitle = string.Empty;
            NewContent = string.Empty;
            SelectedPriority = TodoPriority.None;

            // 通知属性变更
            OnPropertyChanged(nameof(TodoText));
            OnPropertyChanged(nameof(DailyText));
            OnPropertyChanged(nameof(CompletedText));

            // 自动保存
            await ExecuteSaveItems();
        }

        private bool CanExecuteRemoveItem()
        {
            return SelectedItem != null;
        }

        private async void ExecuteRemoveItem()
        {
            if (SelectedItem != null)
            {
                TodoList.RemoveItem(SelectedItem);
                // 通知属性变更
                OnPropertyChanged(nameof(TodoText));
                OnPropertyChanged(nameof(DailyText));
                OnPropertyChanged(nameof(CompletedText));

                // 自动保存
                await ExecuteSaveItems();
            }
        }

        private async Task ExecuteSaveItems()
        {
            try
            {
                await _storageService.SaveItemsAsync(TodoList.Items);
            }
            catch (Exception ex)
            {
                // 错误已经在存储服务中处理
            }
        }

        private async void ExecuteLoadItems()
        {
            try
            {
                var items = await _storageService.LoadItemsAsync();
                TodoList.Items.Clear();
                foreach (var item in items)
                {
                    TodoList.AddItem(item.Title, item.Content, item.Priority);
                    // 恢复其他属性
                    var lastItem = TodoList.Items.Last();
                    lastItem.IsCompleted = item.IsCompleted;
                    lastItem.CreatedDate = item.CreatedDate;
                    lastItem.ShowMenuCommand = ShowMenuCommand;
                }
                // 通知属性变更
                OnPropertyChanged(nameof(TodoCount));
                OnPropertyChanged(nameof(DailyCount));
                OnPropertyChanged(nameof(CompletedCount));
                OnPropertyChanged(nameof(TodoText));
                OnPropertyChanged(nameof(DailyText));
                OnPropertyChanged(nameof(CompletedText));
            }
            catch (Exception ex)
            {
                // 错误已经在存储服务中处理
            }
        }

        private void ExecuteShowMenu(TodoItem item)
        {
            if (item == null) return;

            // 创建上下文菜单
            var menu = new ContextMenu();

            // 添加优先级菜单项
            var priorityMenu = new MenuItem { Header = "优先级" };
            foreach (TodoPriority priority in Enum.GetValues(typeof(TodoPriority)))
            {
                var menuItem = new MenuItem
                {
                    Header = priority.ToString(),
                    IsChecked = item.Priority == priority
                };
                menuItem.Click += (s, e) => TodoList.SetPriority(item, priority);
                priorityMenu.Items.Add(menuItem);
            }
            menu.Items.Add(priorityMenu);

            // 添加完成状态菜单项
            var completeItem = new MenuItem 
            { 
                Header = "完成状态",
                IsChecked = item.IsCompleted
            };
            completeItem.Click += (s, e) => 
            {
                item.IsCompleted = !item.IsCompleted;
                TodoList.UpdateItem(item);
            };
            menu.Items.Add(completeItem);

            // 添加删除菜单项
            var deleteItem = new MenuItem { Header = "删除" };
            deleteItem.Click += (s, e) => TodoList.RemoveItem(item);
            menu.Items.Add(deleteItem);

            // 获取触发菜单的按钮
            if (Mouse.DirectlyOver is FrameworkElement element)
            {
                // 设置菜单的位置
                menu.PlacementTarget = element;
                menu.Placement = PlacementMode.Bottom;
                
                // 显示菜单
                menu.IsOpen = true;
            }
        }

        /// <summary>
        /// 重新排序待办事项
        /// </summary>
        public void ReorderItems(TodoItem sourceItem, TodoItem targetItem)
        {
            if (sourceItem == null || targetItem == null) return;

            int sourceIndex = TodoList.Items.IndexOf(sourceItem);
            int targetIndex = TodoList.Items.IndexOf(targetItem);

            if (sourceIndex != -1 && targetIndex != -1)
            {
                TodoList.Items.Move(sourceIndex, targetIndex);
            }
        }

        /// <summary>
        /// 按优先级排序
        /// </summary>
        private async void ExecuteSortByPriority()
        {
            var sortedItems = TodoList.Items.OrderByDescending(x => x.Priority).ToList();
            TodoList.Items.Clear();
            foreach (var item in sortedItems)
            {
                TodoList.Items.Add(item);
            }
            await ExecuteSaveItems(); // 自动保存排序结果
        }

        /// <summary>
        /// 按创建时间排序
        /// </summary>
        private async void ExecuteSortByTime()
        {
            var sortedItems = TodoList.Items.OrderByDescending(x => x.CreatedDate).ToList();
            TodoList.Items.Clear();
            foreach (var item in sortedItems)
            {
                TodoList.Items.Add(item);
            }
            await ExecuteSaveItems(); // 自动保存排序结果
        }

        /// <summary>
        /// 切换添加面板的显示状态
        /// </summary>
        private void ExecuteToggleAddPanel()
        {
            IsAddPanelExpanded = !IsAddPanelExpanded;
        }
    }
}
